
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter_aliplayer/flutter_aliplayer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_aliplayer/flutter_aliplayer_factory.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:path_provider/path_provider.dart';

import '../service/launchservice/launchservice.dart';
import '../service/request_manager.dart';
import '../tool/player/config.dart';
import '../tool/player/model/playauth_model.dart';
import '../tool/player/page/player_fragment/cache_config_fragment.dart';
import '../tool/player/page/player_fragment/filter_fragment.dart';
import '../tool/player/page/player_fragment/options_fragment.dart';
import 'dart:async';
import 'dart:convert';
import 'dart:io';

import '../tool/player/page/player_fragment/play_config_fragment.dart';
import '../tool/player/page/player_fragment/track_fragment.dart';
import 'aliplayermanger.dart';
class PlayerManager {
  late FlutterAliplayer aliplayer;
  late int bottomIndex;
  late List<Widget> mFramePage;
  late ModeType playMode;
  late Map<String, dynamic> dataSourceMap;
  late OptionsFragment mOptionsFragment;

  //是否允许后台播放
  bool mEnablePlayBack = false;

  //当前播放进度
  int currentPosition = 0;

  //当前播放时间，用于Text展示
  int currentPositionText = 0;

  //当前buffer进度
  int bufferPosition = 0;

  //是否展示loading
  bool showLoading = false;

  //loading进度
  int loadingPercent = 0;

  //视频时长
  int videoDuration = 1;

  //截图保存路径
  late String snapShotPath;

  //提示内容
  late String tipsContent;

  //是否展示提示内容
  bool showTipsWidget = false;

  //是否有缩略图
  bool thumbnailSuccess = false;

  //缩略图
  // Uint8List thumbnailBitmap;
  late ImageProvider imageProvider;

  //当前网络状态
  late ConnectivityResult currentConnectivityResult = ConnectivityResult.none;

  ///seek中
  bool inSeek = false;

  bool isLock = false;

  //网络状态
  bool isShowMobileNetWork = false;

  //当前播放器状态
  int currentPlayerState = 0;

  String extSubTitleText = '';

  ///封面图
  bool showCoverImg = true;

  //网络状态监听
  late StreamSubscription networkSubscription;

  List<int> dotPositionList = [];

  GlobalKey<TrackFragmentState> trackFragmentKey = GlobalKey();

  late int aliPlayerViewId;



  PlayerManager(this.playMode){
    aliplayer = FlutterAliPlayerFactory.createAliPlayer();
    //开启混音模式
    if (Platform.isIOS) {
      FlutterAliplayer.setAudioSessionTypeForIOS(
          AliPlayerAudioSesstionType.mix);
    }

    //设置播放器
    aliplayer.setPreferPlayerName(GlobalSettings.mPlayerName);
    aliplayer.setEnableHardwareDecoder(GlobalSettings.mEnableHardwareDecoder);

    if (Platform.isAndroid) {
      // MARK: 是安卓手机的情况下，获取外部存储路径。
      getExternalStorageDirectories().then(
            (value) {
          if (value != null && value.isNotEmpty) {
            snapShotPath = value[0].path;
            return snapShotPath;
          }
        },
      );
    }
    mOptionsFragment = OptionsFragment(aliplayer);
    mFramePage = [
      mOptionsFragment,
      PlayConfigFragment(aliplayer),
      FilterFragment(aliplayer),
      CacheConfigFragment(aliplayer),
      TrackFragment(trackFragmentKey, aliplayer),
    ];

    mOptionsFragment.setOnEnablePlayBackChanged(
          (mEnablePlayBack) {
        mEnablePlayBack = mEnablePlayBack;
      },
    );


  }
  ///视频id
  int kid = 0;
  Future<Map<String, String>> requestAuth() async {
    try {
      final model = await AliPlayerManger.getInstance()
          .requestPlayAuth(kid: kid, authType: VideoAuthType.online);
      var map = {
        DataSourceRelated.VID_KEY: model?.vid ?? "",
        DataSourceRelated.REGION_KEY: "cn-shanghai",
        DataSourceRelated.PLAYAUTH_KEY:
        model?.playauth ?? "",
        // DataSourceRelated.PREVIEWTIME_KEY:
        // _previewController.text,
        // DataSourceRelated.DEFINITION_LIST: _definitionList
      };
      return map;
    }catch (e) {
      return {};
    }

  }


  Future<Map<String, String>> requestAuthByAlivid(String alivid) async {

      final url = LaunchService.getInstance().config?.api?.videoPlayAuthByAliVid ?? "";
      final response = await RequestManager
          .getInstance()
          .dio
          .get(url, queryParameters: {"alivid": alivid});
      final data = response.data as Map<String, dynamic>;
      final dict = data["data"] as Map<String, dynamic>;
      final model = PlayAuthModel.fromJson(dict);
      var map = {
        DataSourceRelated.VID_KEY: model.vid ?? "",
        DataSourceRelated.REGION_KEY: "cn-shanghai",
        DataSourceRelated.PLAYAUTH_KEY:
        model.playauth ?? "",
        // DataSourceRelated.PREVIEWTIME_KEY:
        // _previewController.text,
        // DataSourceRelated.DEFINITION_LIST: _definitionList
      };
      return map;


  }


  setNetworkChangedListener({required Function(bool) block}) {
    networkSubscription = Connectivity().onConnectivityChanged.listen(
          (ConnectivityResult result) {
        if (result == ConnectivityResult.mobile) {
          aliplayer.pause();
          isShowMobileNetWork = true;

          block(isShowMobileNetWork);

        } else if (result == ConnectivityResult.wifi) {
          //从4G网络或者无网络切换到wifi
          if (currentConnectivityResult == ConnectivityResult.mobile ||
              currentConnectivityResult == ConnectivityResult.none) {
            aliplayer.play();
          }
          isShowMobileNetWork = false;

          block(isShowMobileNetWork);

        }
        currentConnectivityResult = result;
      },
    );
  }
  // initListener() {
  //   aliplayer.setOnEventReportParams(
  //         (params, playerId) {
  //       print("EventReportParams=${params}");
  //     },
  //   );
  //   aliplayer.setOnPrepared(
  //         (playerId) {
  //       Fluttertoast.showToast(msg: "OnPrepared ");
  //       aliplayer.getPlayerName().then(
  //             (value) => print("getPlayerName==${value}"),
  //       );
  //       aliplayer.getMediaInfo().then(
  //             (value) {
  //           videoDuration = value['duration'];
  //           // setState(() {});
  //         },
  //       );
  //     },
  //   );
  //   aliplayer.setOnRenderingStart(
  //         (playerId) {
  //       Fluttertoast.showToast(msg: " OnFirstFrameShow ");
  //       // setState(
  //       //       () {
  //       //     if (mounted) {
  //       //       _showCoverImg = false;
  //       //     }
  //       //   },
  //       // );
  //     },
  //   );
  //   aliplayer.setOnVideoSizeChanged((width, height, rotation, playerId) {});
  //   aliplayer.setOnStateChanged(
  //         (newState, playerId) {
  //       currentPlayerState = newState;
  //       switch (newState) {
  //         case FlutterAvpdef.AVPStatus_AVPStatusStarted:
  //           // setState(
  //           //       () {
  //           //     _showTipsWidget = false;
  //           //     _showLoading = false;
  //           //   },
  //           // );
  //           break;
  //         case FlutterAvpdef.AVPStatus_AVPStatusPaused:
  //           break;
  //         default:
  //       }
  //     },
  //   );
  //   aliplayer.setOnLoadingStatusListener(
  //     loadingBegin: (playerId) {
  //       // setState(
  //       //       () {
  //       //     loadingPercent = 0;
  //       //     showLoading = true;
  //       //   },
  //       // );
  //     },
  //     loadingProgress: (percent, netSpeed, playerId) {
  //       loadingPercent = percent;
  //       if (percent == 100) {
  //         showLoading = false;
  //       }
  //       // setState(() {});
  //     },
  //     loadingEnd: (playerId) {
  //       // setState(
  //       //       () {
  //       //     _showLoading = false;
  //       //   },
  //       // );
  //     },
  //   );
  //   aliplayer.setOnSeekComplete(
  //         (playerId) {
  //       inSeek = false;
  //     },
  //   );
  //   aliplayer.setOnInfo(
  //         (infoCode, extraValue, extraMsg, playerId) {
  //       if (infoCode == FlutterAvpdef.CURRENTPOSITION) {
  //         if (_videoDuration != 0 && extraValue != null &&extraValue <= _videoDuration) {
  //           _currentPosition = extraValue;
  //         }
  //         if (!_inSeek) {
  //           setState(
  //                 () {
  //               _currentPositionText = extraValue  ?? 0;
  //             },
  //           );
  //         }
  //       } else if (infoCode == FlutterAvpdef.BUFFEREDPOSITION) {
  //         _bufferPosition = extraValue ?? 0;
  //         if (mounted) {
  //           setState(() {});
  //         }
  //       } else if (infoCode == FlutterAvpdef.AUTOPLAYSTART) {
  //         Fluttertoast.showToast(msg: "AutoPlay");
  //       } else if (infoCode == FlutterAvpdef.CACHESUCCESS) {
  //         Fluttertoast.showToast(msg: "Cache Success");
  //       } else if (infoCode == FlutterAvpdef.CACHEERROR) {
  //         Fluttertoast.showToast(msg: "Cache Error $extraMsg");
  //       } else if (infoCode == FlutterAvpdef.LOOPINGSTART) {
  //         Fluttertoast.showToast(msg: "Looping Start");
  //       } else if (infoCode == FlutterAvpdef.SWITCHTOSOFTWAREVIDEODECODER) {
  //         Fluttertoast.showToast(msg: "change to soft ware decoder");
  //         mOptionsFragment.switchHardwareDecoder();
  //       }
  //     },
  //   );
  //   aliplayer.setOnCompletion(
  //         (playerId) {
  //       _showTipsWidget = true;
  //       _showLoading = false;
  //       _tipsContent = "播放完成";
  //       setState(
  //             () {
  //           _currentPosition = _videoDuration;
  //         },
  //       );
  //     },
  //   );
  //   aliplayer.setOnTrackReady(
  //         (playerId) {
  //       aliplayer.getMediaInfo().then(
  //             (value) {
  //           setState(() {});
  //           List thumbnails = value['thumbnails'];
  //           if (thumbnails != null && thumbnails.isNotEmpty) {
  //             aliplayer.createThumbnailHelper(thumbnails[0]['url']);
  //           } else {
  //             _thumbnailSuccess = false;
  //           }
  //         },
  //       );
  //       trackFragmentKey.currentState?.loadData();
  //       setState(() {});
  //     },
  //   );
  //
  //   aliplayer.setOnSnapShot((path, playerId) {
  //     Fluttertoast.showToast(msg: "SnapShot Save : $path");
  //   });
  //   aliplayer.setOnError(
  //         (errorCode, errorExtra, errorMsg, playerId) {
  //       _showTipsWidget = true;
  //       _showLoading = false;
  //       _tipsContent = "$errorCode \n $errorMsg";
  //       setState(() {});
  //     },
  //   );
  //
  //   aliplayer.setOnTrackChanged(
  //         (value, playerId) {
  //       AVPTrackInfo info = AVPTrackInfo.fromJson(value);
  //       if (info != null && info.trackDefinition != null && info.trackDefinition!.isNotEmpty) {
  //         trackFragmentKey.currentState?.onTrackChanged(info);
  //         Fluttertoast.showToast(msg: "${info.trackDefinition}切换成功");
  //       }
  //     },
  //   );
  //
  //   aliplayer.setOnThumbnailPreparedListener(
  //     preparedSuccess: (playerId) {
  //       _thumbnailSuccess = true;
  //       setState(() {
  //         /// 打点位置
  //         dotPositionList.add(30000);
  //         dotPositionList.add(65000);
  //         dotPositionList.add(125000);
  //       });
  //     },
  //     preparedFail: (playerId) {
  //       _thumbnailSuccess = false;
  //     },
  //   );
  //
  //   aliplayer.setOnThumbnailGetListener(
  //       onThumbnailGetSuccess: (bitmap, range, playerId) {
  //         // _thumbnailBitmap = bitmap;
  //         var provider = MemoryImage(bitmap);
  //         precacheImage(provider, context).then(
  //               (_) {
  //             setState(
  //                   () {
  //                 _imageProvider = provider;
  //               },
  //             );
  //           },
  //         );
  //       },
  //       onThumbnailGetFail: (playerId) {});
  //
  //   aliplayer.setOnSubtitleHide(
  //         (trackIndex, subtitleID, playerId) {
  //       if (mounted) {
  //         setState(
  //               () {
  //             extSubTitleText = '';
  //           },
  //         );
  //       }
  //     },
  //   );
  //
  //   aliplayer.setOnSubtitleShow(
  //         (trackIndex, subtitleID, subtitle, playerId) {
  //       if (mounted) {
  //         setState(
  //               () {
  //             extSubTitleText = subtitle;
  //           },
  //         );
  //       }
  //     },
  //   );
  //   _setNetworkChangedListener();
  // }





  generatePlayConfigGen() {
    FlutterAliplayer.createVidPlayerConfigGenerator();
    FlutterAliplayer.setPreviewTime(0);
  }

  dispose() {
    aliplayer.stop();
    aliplayer.destroy();
    if (networkSubscription != null) {
      networkSubscription.cancel();
    }
  }








}